package com.egg.ylt.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.egg.ylt.R;
import com.egg.ylt.Utils.API;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.adapter.ADA_OtherMealCardAdapter;
import com.egg.ylt.adapter.ADA_StoreListAdapter;
import com.egg.ylt.pojo.ShopCardByIdEntity;
import com.egg.ylt.presenter.impl.TimeCardDetailsPresenterImpl;
import com.egg.ylt.view.ITimeCardDetailsView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.CommonUtils;
import com.yonyou.framework.library.common.utils.AppSharedPreferences;
import com.yonyou.framework.library.common.utils.ToastUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ACT_MealCardDetails extends BaseActivity<TimeCardDetailsPresenterImpl> implements ITimeCardDetailsView {

    @BindView(R.id.title_rl)
    RelativeLayout mTitleRl;

    @BindView(R.id.loading_target_view)
    FrameLayout mLoadingTargetView;

    @BindView(R.id.collect_iv)
    ImageView mCollectIv;

    @BindView(R.id.banner)
    Banner mBanner;

    @BindView(R.id.name_tv)
    TextView mNameTv;

    @BindView(R.id.reserved_count_tv)
    TextView mReservedCountTv;

    @BindView(R.id.description_tv)
    TextView mDescriptionTv;

    @BindView(R.id.store_list_rlv)
    RecyclerView mStoreListRlv;

    @BindView(R.id.meal_card_name_tv)
    TextView mMealCardNameTv;

    @BindView(R.id.times_tv)
    TextView mTimesTv;

    @BindView(R.id.price_per_time_tv)
    TextView mPricePerTimeTv;

    @BindView(R.id.total_price_tv)
    TextView mTotalPriceTv;

    @BindView(R.id.meal_card_price_tv)
    TextView mMealCardPriceTv;

    @BindView(R.id.meal_card_contains_content_tv)
    TextView mMealCardContainsContentTv;

    @BindView(R.id.validity_period_tv)
    TextView mValidityPeriodTv;

    @BindView(R.id.except_date_tv)
    TextView mExceptDateTv;

    @BindView(R.id.use_time_tv)
    TextView mUseTimeTv;

    @BindView(R.id.reservation_information_tv)
    TextView mReservationInformationTv;

    @BindView(R.id.applicable_number_tv)
    TextView mApplicableNumberTv;

    @BindView(R.id.suitable_for_the_crowd_tv)
    TextView mSuitableForTheCrowdTv;

    @BindView(R.id.rule_reminder_tv)
    TextView mRuleReminderTv;

    @BindView(R.id.other_meal_card_rlv)
    RecyclerView mOtherMealCardRlv;

    @BindView(R.id.price_tv)
    TextView mPriceTv;

    @BindView(R.id.old_price_tv)
    TextView mOldPriceTv;


    private ADA_StoreListAdapter mStoreListAdapter;
    private ADA_OtherMealCardAdapter mOtherMealCardAdapter;

    private String mCardId;
    private String mShopId;
    private String mShopName;
    private String mCardImageUrl;
    private boolean mIsCollected = false;
    private ShopCardByIdEntity mCardEntity;
    private com.yonyou.framework.library.dialog.AlertDialog mShareDialog;
    private String mOpenTime;

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_meal_card_details;
    }

    @Override
    protected View getLoadingTargetView() {
        return mLoadingTargetView;
    }

    @Override
    protected void initViewsAndEvents() {
        StatusBarUtil.setStatusBarColor(this, R.color.ylt_whit);
        StatusBarUtil.StatusBarLightMode(this);
        CustomUtils.setImmersiveStatusBar(mContext, mTitleRl);

        Intent intent = getIntent();
        //得到传过来的次卡ID
        mCardId = intent.getStringExtra("cardId");

        mShopId = intent.getStringExtra("shopId");

        mShopName = intent.getStringExtra("shopName");

        mCardImageUrl = intent.getStringExtra("cardImageUrl");

        mOpenTime = intent.getStringExtra("openTime");

        //请求次卡详情数据
        mPresenter.getTimeCardData(Constants.TOKEN, mCardId, mShopId);
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @OnClick({R.id.back_iv, R.id.share_iv, R.id.collect_iv, R.id.see_detail_rl, R.id.order_now_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_iv://返回键
                finish();
                break;
            case R.id.share_iv:
                umShareDialogShow();
                break;
            case R.id.collect_iv:
                if (StringUtil.isEmpty(Constants.TOKEN)) {
                    readyGo(ACT_UserLogin.class);
                    return;
                }
                if (mIsCollected) {
                    mPresenter.setCancelMessage(Constants.TOKEN, mShopId);
                } else {
                    mPresenter.setCollectMessage(Constants.TOKEN, mShopId, Constants.COMPANYID);
                }
                break;
            case R.id.see_detail_rl:
                Bundle b = new Bundle();
                b.putSerializable("title", "次卡详情");
                b.putSerializable("url", API.TIME_CARD_SHARE_URL + "?token=" + Constants.TOKEN + "&id=" + mCardId +
                        "&shopId=" + mShopId + "&isShare=false#/timeInfo");
                readyGo(ACT_WebView.class, b);
                break;
            case R.id.order_now_tv://去购买
                Bundle bundle = new Bundle();
                bundle.putString("shopName", mShopName);
                bundle.putString("cardImageUrl", mCardImageUrl);
                bundle.putString("cardId", mCardEntity.getId());
                bundle.putString("cardName", mCardEntity.getName());
                bundle.putString("price", mCardEntity.getPrice());
                bundle.putString("endDate", mCardEntity.getEndDate());
                bundle.putString("applyType", "2");
                bundle.putString("shopId", mShopId);
                readyGo(ACT_ConfirmPayment.class, bundle);
                break;
        }
    }

    @Override
    public void getTimeCard(ShopCardByIdEntity entity) {
        if (entity == null || StringUtil.isEmpty(entity.getId())) {
            return;
        }
        mCardEntity = entity;

        //Banner
        List<ShopCardByIdEntity.BannerListEntity> bannerEntities = entity.getBannerList();
        if (bannerEntities != null && !bannerEntities.isEmpty()) {
            List<String> imageUrls = new ArrayList<>();
            final List<String> titles = new ArrayList<>();
            for (int i = 0; i < bannerEntities.size(); i++) {
                titles.add("");
                imageUrls.add(bannerEntities.get(i).getImageUrl());
            }
            //设置banner样式
            mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            //设置图片加载器
            mBanner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    if (context != null) {
                        //Glide 加载图片简单用法
                        Glide.with(context).load(path).error(R.mipmap.ic_banner_default).dontAnimate().placeholder(R.mipmap.ic_banner_default).into(imageView);
                    }
                }
            });
            //设置图片集合
            mBanner.setImages(imageUrls);
            //设置banner动画效果
            mBanner.setBannerAnimation(Transformer.DepthPage);
            //设置标题集合（当banner样式有显示title时）
            mBanner.setBannerTitles(titles);
            //设置自动轮播，默认为true
            mBanner.isAutoPlay(true);
            //设置轮播时间
            mBanner.setDelayTime(3000);
            //设置指示器位置（当banner模式中有指示器时）
            mBanner.setIndicatorGravity(BannerConfig.CENTER);
        }
        //banner设置方法全部调用完毕时最后调用
        mBanner.start();

        //展示次卡详情数据
        mNameTv.setText(entity.getName());
        mDescriptionTv.setText(entity.getServiceIntro());
        mReservedCountTv.setText("已售" + entity.getSellNum());


        mStoreListRlv.setNestedScrollingEnabled(false);
        mStoreListRlv.setLayoutManager(new LinearLayoutManager(this));
        if (mStoreListAdapter == null) {
            mStoreListAdapter = new ADA_StoreListAdapter(entity.getShopList());
            mStoreListRlv.setAdapter(mStoreListAdapter);
        } else {
            mStoreListAdapter.notifyDataSetChanged();
        }

        mMealCardNameTv.setText(entity.getName());

        mTimesTv.setText(entity.getTimes() + "次");

        mPricePerTimeTv.setText(StringUtil.getBigDecimalPrice(entity.getUnitPrice()) + "元/次");

        mTotalPriceTv.setText(StringUtil.getBigDecimalPrice(entity.getTotalPrice()) + "元");

        mMealCardPriceTv.setText(StringUtil.getBigDecimalPrice(entity.getPrice()) + "元");

        mMealCardContainsContentTv.setText(entity.getServiceDetail());

        mValidityPeriodTv.setText(entity.getValidDay() + "月");

        mExceptDateTv.setText(entity.getUseExcludeDate());

        mUseTimeTv.setText(mOpenTime);

        mReservationInformationTv.setText(entity.getAppointmentMsg());

        if (CommonUtils.isEmpty(entity.getFitPerNum())) {
            mApplicableNumberTv.setText("不限制");
        } else {
            mApplicableNumberTv.setText("每张次卡最多" + entity.getFitPerNum() + "人使用");
        }

        if (CommonUtils.isEmpty(entity.getFitAge())) {
            mSuitableForTheCrowdTv.setText("年龄群体：不限制");
        } else {
            mSuitableForTheCrowdTv.setText("年龄群体：" + entity.getFitAge() + "岁");
        }

        mRuleReminderTv.setText(entity.getRuleHint());

        mPriceTv.setText(StringUtil.getBigDecimalPrice(entity.getPrice()));

        mOldPriceTv.setText("¥" + StringUtil.getBigDecimalPrice(entity.getTotalPrice()));

        mOtherMealCardRlv.setLayoutManager(new LinearLayoutManager(this));
        mOtherMealCardRlv.setNestedScrollingEnabled(false);
        if (mOtherMealCardAdapter == null) {
            mOtherMealCardAdapter = new ADA_OtherMealCardAdapter(mShopId, mOpenTime);
            mOtherMealCardRlv.setAdapter(mOtherMealCardAdapter);
            mOtherMealCardAdapter.setData(entity.getCardList());
        } else {
            mOtherMealCardAdapter.notifyDataSetChanged();
        }
        CustomUtils.setMiddleLine(mOldPriceTv);
    }

    @Override
    public void cancelCollect() {
        mIsCollected = false;
        changeCollected();
    }

    @Override
    public void doCollect() {
        mIsCollected = true;
        changeCollected();
    }

    private void changeCollected() {
        mCollectIv.setSelected(mIsCollected);
    }

    /**
     * 分享的dialog展示
     */
    public void umShareDialogShow() {
        //判断不为空直接关闭
        if (mShareDialog != null) {
            mShareDialog.dismiss();
        }
        //友盟分享链接的对象
        String uri =
                API.TIME_CARD_SHARE_URL + "?token=" + Constants.TOKEN + "&id=" + mCardId + "&shopId=" + mShopId +
                        "&isShare=false#/timeInfo";
        final UMWeb web = new UMWeb(uri);
        web.setTitle(" ");
        web.setDescription(" ");
        mShareDialog = new com.yonyou.framework.library.dialog.AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_um_share_view)
                .setCancelableOntheOutside(true)
                .setWidthAndHeight(mScreenWidth, 900)
                .fromBottom(true)
                .create();
        //设置点击事件
        //微信好友
        mShareDialog.setOnClickListener(R.id.btn_share_wx, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mm")) {
                    new ShareAction(mContext)
                            .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                            .withMedia(web)//分享链接
                            .setCallback(shareListener)//回调监听器
                            .share();
                } else {
                    ToastUtil.makeText(mContext, "微信未安装", false);
                }
            }
        });
        //QQ空间
        mShareDialog.setOnClickListener(R.id.btn_share_qq_space, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isInstallByread("com.tencent.mobileqq")) {
                    new ShareAction(mContext)
                            .setPlatform(SHARE_MEDIA.QZONE)//传入平台
                            .withMedia(web)//分享链接
                            .setCallback(shareListener)//回调监听器
                            .share();
                } else {
                    ToastUtil.makeText(mContext, "QQ应用未安装", false);
                }
            }
        });
        //新浪微博
        mShareDialog.setOnClickListener(R.id.btn_share_sina, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ShareAction(mContext)
                        .setPlatform(SHARE_MEDIA.SINA)//传入平台
                        .withMedia(web)//分享链接
                        .setCallback(shareListener)//回调监听器
                        .share();
            }
        });
        //QQ好友
        mShareDialog.setOnClickListener(R.id.btn_share_qq_friend, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mobileqq")) {
                    new ShareAction(mContext)
                            .setPlatform(SHARE_MEDIA.QQ)//传入平台
                            .withMedia(web)//分享链接
                            .setCallback(shareListener)//回调监听器
                            .share();
                } else {
                    ToastUtil.makeText(mContext, "QQ应用未安装", false);
                }
            }
        });
        //微信朋友圈
        mShareDialog.setOnClickListener(R.id.btn_share_circle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mm")) {
                    new ShareAction(mContext)
                            .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                            .withMedia(web)//分享链接
                            .setCallback(shareListener)//回调监听器
                            .share();
                } else {
                    ToastUtil.makeText(mContext, "微信未安装", false);
                }
            }
        });
        //取消dialog
        mShareDialog.setOnClickListener(R.id.btn_share_cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mShareDialog != null) {
                    mShareDialog.dismiss();
                }
            }
        });
        //展示
        mShareDialog.show();

    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(mContext, "分享成功", Toast.LENGTH_LONG).show();
            //判断不为空直接关闭
            if (mShareDialog != null) {
                mShareDialog.dismiss();
            }
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(mContext, "分享失败" + t.getMessage(), Toast.LENGTH_LONG).show();
            //判断不为空直接关闭
            if (mShareDialog != null) {
                mShareDialog.dismiss();
            }
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            if (platform.getName().equals("QQ")) {

            } else {
                Toast.makeText(mContext, "取消分享", Toast.LENGTH_LONG).show();
            }
            //判断不为空直接关闭
            if (mShareDialog != null) {
                mShareDialog.dismiss();
            }

        }
    };

    /**
     * 判断是否安装目标应用
     *
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }
}
